﻿using AFanDa.BLL.BLLService;
using AFanDa.Dto.Request;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
using System.Web;
using System.Web.Http;

namespace AFanDa.Api.Controllers
{
    public class OrderController : ApiController
    {
        OrderService _orderService = null;

        /// <summary>
        /// 
        /// </summary>
        public OrderController()
        {
            _orderService = new OrderService();
        }

        /// <summary>
        /// 生成订单
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        public IHttpActionResult CreateOrder(OrderRequestDto dto)
        {
            var result = _orderService.CreateOrder(dto);
            return Ok(result);
        }
        /// <summary>
        /// 获取单个订单
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IHttpActionResult GetOrderInfo(string Oid)
        {
            var result = _orderService.GetOrderInfo(new Dto.Request.OrderRequestDto()
            {
                id = Oid
            });
            return Ok(result);
        }
        /// <summary>
        /// 获取用户订单
        /// </summary>
        /// <param name="uid"></param>
        /// <returns></returns>
        [HttpGet]
        public IHttpActionResult GetOrderByStatu(string uid)
        {
            var result = _orderService.GetOrderByStatu(new OrderRequestDto()
            {
                Uid = uid
            });

            return Ok(result);
        }

        /// <summary>
        /// 修改订单状态
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        public IHttpActionResult UpdateOrderState(OrderRequestDto dto)
        {

            var result = _orderService.UpdateOrderState(dto);
            return Ok(result);


        }

        /// <summary>
        /// 支付成功后的回调接口
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IHttpActionResult NotifyUrl()
        {

            var tradeOrderId = HttpContext.Current.Request["trade_order_id"];

            //去拿着订单号 查询数据库  并修改之

            var totalFee = HttpContext.Current.Request["total_fee"];
            var transactionId = HttpContext.Current.Request["transaction_id"];
            var plugins = HttpContext.Current.Request["plugins"];
            var status = HttpContext.Current.Request["status"];
            var hash = HttpContext.Current.Request["hash"];

            string path = $"C:/guigu/02/pay/Logs/{DateTime.Now.ToString("yyyyMMdd")}.txt";
            System.IO.File.AppendAllText(path, $"真的回调了,订单号【{tradeOrderId}】");


            return Ok(!string.IsNullOrEmpty(tradeOrderId) ? "success" : "");
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>

        [HttpPost]
        public IHttpActionResult DelGoods(string id)
        {
            return Ok(_orderService.DelGoods(id));
        }

        /// <summary>
        /// 生成支付链接
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        public IHttpActionResult Pay(OrderRequestDto dto)
        {
            var result = _orderService.PayOrder(dto);
            if (result.code == Dto.Base.ApiCode.fail)
            {
                //失败了
                return Ok(result);
            }


            var json = new JObject();

            try
            {
                var dic = new Dictionary<string, string>
                {
                    {"version", "1.1"},
                    {"lang", "zh-cn"},
                    {"plugins", "test-001"},
                    {"appid", "201906136505"},//appid
                    {"appsecret", "160130736b1ac0d54ed7abe51e44840b"},//appsecret
                    {"trade_order_id", dto.id},//订单号
                    {"payment", "wechat"},//支付类型
                    {"total_fee", "0.01"},//金额
                    {"title", "pay"},//标题，只能数据字或英文（中文乱码，找不到原因）
                    {"time", Common.Config.GetTimeStamp().ToString()},//时间戳
                    {"notify_url", "http://124.222.120.73/api/Pay/NotifyUrl"},//通知链接
                    {"return_url", "http://localhost:8080/#/pages/PayOk/PayOk?id="+dto.id},//跳转链接
                    {"nonce_str", Common.Config.GUID()},//随机字符串
                };

                dic.Add("hash", Sign(dic));

                var sr = JsonConvert.DeserializeObject<SamplesResult>(PostHttp(dic));

                json.Add(new JProperty("openid", sr.Openid));
                json.Add(new JProperty("url", sr.Url));
                json.Add(new JProperty("errcode", sr.Errcode));
                json.Add(new JProperty("errmsg", sr.Errmsg));
                json.Add(new JProperty("hash", sr.Hash));
            }
            catch (Exception e)
            {
                throw e;
            }

            return Ok(json.ToString());
        }

        public class SamplesResult
        {
            public string Openid { get; set; }

            public string Url { get; set; }

            public string Errcode { get; set; }

            public string Errmsg { get; set; }

            public string Hash { get; set; }
        }



        public static string PostHttp(Dictionary<string, string> dicArray)
        {
            string result;

            try
            {
                var req = (HttpWebRequest)WebRequest.Create("https://api.xunhupay.com/payment/do.html");
                req.KeepAlive = false;
                req.Method = "POST";
                req.ContentType = "application/x-www-form-urlencoded";
                req.Accept = "application/json";

                var paramData = ParamData(dicArray);
                var data = Encoding.Default.GetBytes(paramData);

                req.ContentLength = data.Length;

                var swrite = req.GetRequestStream();
                swrite.Write(data, 0, data.Length);
                swrite.Close();

                var resp = (HttpWebResponse)req.GetResponse();
                var stream = resp.GetResponseStream();

                //获取响应内容
                var reader = new StreamReader(stream ?? throw new InvalidOperationException(), Encoding.UTF8);
                result = reader.ReadToEnd();
            }
            catch (WebException ex)
            {
                result = ex.Message;
            }

            return result;
        }

        public static string Sign(Dictionary<string, string> dicArray)
        {
            var prestr = new StringBuilder();
            foreach (var temp in dicArray.OrderBy(o => o.Key))
            {
                prestr.Append(temp.Key + "=" + temp.Value + "&");
            }
            var nLen = prestr.Length;
            prestr.Remove(nLen - 1, 1);
            var signValue = Md5Encoder(prestr + "4d073f520cc2e723ee13a5227bf1bd27", 32);
            return signValue;
        }

        public static string ParamData(Dictionary<string, string> dicArray)
        {
            var prestr = new StringBuilder();
            foreach (var temp in dicArray)
            {
                prestr.Append(temp.Key + "=" + temp.Value + "&");
            }

            var nLen = prestr.Length;
            prestr.Remove(nLen - 1, 1);

            return prestr.ToString();
        }

        public static string Md5Encoder(string str, int bit)
        {
            var md5Hasher = new MD5CryptoServiceProvider();
            var hashedDataBytes = md5Hasher.ComputeHash(Encoding.GetEncoding("gb2312").GetBytes(str));
            var tmp = new StringBuilder();
            foreach (var i in hashedDataBytes)
            {
                tmp.Append(i.ToString("x2"));
            }

            switch (bit)
            {
                case 16:
                    return tmp.ToString().Substring(8, 16);
                case 32:
                    return tmp.ToString();//默认情况
            }

            return string.Empty;
        }

        /// <summary>
        /// 余额支付
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IHttpActionResult PayMyMoney(Dto.Request.OrderRequestDto dto)
        {
            var result = _orderService.PayMyMoney(dto);
            return Ok(result);
        }

    }
}
